<template>
  <div class="consult-chat-container">
    <!-- 顶部进度条 -->
    <div class="chat-header">
      <div class="progress-info">
        <span class="progress-text">{{ currentStep }}/{{ totalSteps }} 症状描述中</span>
        <el-progress :percentage="progressPercentage" size="small" :stroke-width="4" />
      </div>
      <el-button 
        type="text" 
        class="end-btn"
        @click="confirmEndChat"
      >
        <el-icon><PhoneFilled /></el-icon>
        结束会话
      </el-button>
    </div>
    
    <!-- 数字人+对话区 -->
    <div class="chat-content">
      <!-- 左侧数字人 -->
      <div class="chat-human">
        <DigitalHuman 
          :emotion="digitalHumanEmotion" 
          :action="digitalHumanAction" 
          @onAnimationEnd="onDigitalHumanAnimationEnd"
        />
        <!-- 数字人状态提示 -->
        <div class="human-status" v-if="isRecording || isLoading">
          <span v-if="isRecording">正在倾听...</span>
          <span v-if="isLoading">正在思考...</span>
        </div>
      </div>
      
      <!-- 右侧对话气泡区 -->
      <div class="chat-bubbles" ref="chatContainer">
        <!-- 系统欢迎消息（初始加载） -->
        <ChatBubble 
          v-if="messages.length === 0" 
          :message="welcomeMessage" 
        />
        
        <!-- 对话消息列表 -->
        <ChatBubble 
          v-for="(msg, idx) in messages" 
          :key="msg.id"
          :message="msg"
        />
        
        <!-- 系统加载中动画 -->
        <div class="bubble system-bubble loading-bubble" v-if="isLoading">
          <div class="bubble-header">
            <span class="bubble-name">智能导诊助手</span>
            <span class="bubble-time">{{ formatTime(new Date()) }}</span>
          </div>
          <div class="bubble-content">
            <el-skeleton :rows="2" :width="['80%', '60%']" />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部输入区 -->
    <div class="chat-input">
      <div class="input-tools">
        <!-- 语音录制按钮 -->
        <el-button 
          class="voice-btn"
          :icon="isRecording ? MicrophoneFilled : Microphone"
          :type="isRecording ? 'primary' : 'default'"
          @mousedown="startRecording"
          @mouseup="stopRecording"
          @mouseleave="handleRecordCancel"
          @touchstart="startRecording"
          @touchend="stopRecording"
          :disabled="isLoading"
        />
        <span class="recording-time" v-if="isRecording">{{ recordingTime }}s</span>
      </div>
      <el-input
        v-model="inputContent"
        class="input-box"
        placeholder="请描述您的症状，例如‘最近胃痛、反酸’..."
        @keyup.enter="sendTextMessage"
        :disabled="isRecording || isLoading || !isConnected"
      />
      <el-button 
        class="send-btn"
        type="primary"
        @click="sendTextMessage"
        :disabled="!inputContent.trim() || isRecording || isLoading || !isConnected"
      >
        发送
      </el-button>
    </div>
    
    <!-- 连接状态提示 -->
    <div class="connection-status" v-if="!isConnected">
      <el-alert 
        title="连接已断开，正在重连..." 
        type="warning" 
        :closable="false"
        show-icon
      />
    </div>
    
    <!-- 结束会话确认弹窗 -->
    <el-dialog v-model="endDialogVisible" title="结束会话" width="30%">
      <p>确定要结束当前问诊会话吗？未完成的问诊记录将被保存。</p>
      <template #footer>
        <el-button @click="endDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="endChat">确认结束</el-button>
      </template>
    </el-dialog>
    
    <!-- 录音取消确认弹窗 -->
    <el-dialog v-model="cancelRecordDialogVisible" title="取消录音" width="30%">
      <p>确定要取消当前录音吗？</p>
      <template #footer>
        <el-button @click="continueRecording">继续录音</el-button>
        <el-button type="primary" @click="confirmCancelRecording">确认取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import { ElButton, ElInput, ElProgress, ElDialog, ElSkeleton, ElIcon, ElMessage, ElAlert } from 'element-plus'
import { PhoneFilled, Microphone, MicrophoneFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useConsultStore } from '@/stores/consult'
import DigitalHuman from '@/views/home/DigitalHuman.vue'
import ChatBubble from './ChatBubble.vue'

// 路由实例
const router = useRouter()

// Store实例
const consultStore = useConsultStore()

// 解构Store状态和方法
const { 
  messages, 
  currentStep, 
  totalSteps, 
  isRecording, 
  recordingTime, 
  isLoading, 
  isConnected, 
  digitalHumanEmotion, 
  digitalHumanAction, 
  progressPercentage,
  submitTextMessage, 
  startRecording, 
  stopRecording, 
  endConsultation,
  MESSAGE_TYPES
} = consultStore

// 本地状态
const inputContent = ref('') // 文字输入内容
const endDialogVisible = ref(false)
const cancelRecordDialogVisible = ref(false)
const isMouseDown = ref(false)
const cancelTimer = ref(null)

// 对话容器引用（用于自动滚动到底部）
const chatContainer = ref(null)

// 欢迎消息
const welcomeMessage = {
  type: MESSAGE_TYPES.SYSTEM,
  content: '您好！请描述您的症状（如"最近胃痛、反酸"），我会帮您分析并推荐科室～',
  time: new Date(),
  id: 'welcome-' + Date.now()
}

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
  })
}, { deep: true })

// 监听步骤变化，到达最后一步且有科室推荐时跳转
watch(currentStep, (newStep) => {
  if (newStep >= totalSteps.value && consultStore.hasMessages) {
    const hasRecommendations = consultStore.departmentRecommendations.length > 0
    if (hasRecommendations) {
      setTimeout(() => {
        router.push('/department-recommend')
      }, 3000)
    }
  }
})

// 监听连接状态变化
watch(isConnected, (connected) => {
  if (!connected) {
    // 模拟重连
    setTimeout(() => {
      consultStore.isConnected = true
      ElMessage.success('已重新连接')
    }, 3000)
  }
})

// 页面加载时初始化会话
onMounted(() => {
  // 添加全局鼠标事件监听
  document.addEventListener('mouseup', handleGlobalMouseUp)
  
  // 从路由参数获取输入类型（语音/文字）
  const inputType = router.currentRoute.value.query.inputType
  if (inputType === 'voice') {
    // 自动触发语音输入提示
    setTimeout(() => {
      startRecording()
    }, 1000)
  }
})

// 页面卸载时清理
onUnmounted(() => {
  document.removeEventListener('mouseup', handleGlobalMouseUp)
  if (cancelTimer.value) {
    clearTimeout(cancelTimer.value)
  }
})

// 发送文字消息
const sendTextMessage = () => {
  if (!inputContent.value.trim()) return
  
  // 调用store方法发送消息
  submitTextMessage(inputContent.value.trim())
  
  // 清空输入框
  inputContent.value = ''
}

// 处理数字人动画结束事件
const onDigitalHumanAnimationEnd = () => {
  // 动画结束后的处理逻辑
}

// 全局鼠标抬起事件处理
const handleGlobalMouseUp = () => {
  if (isMouseDown.value && isRecording.value) {
    // 意外松开，显示确认弹窗
    handleRecordCancel()
  }
  isMouseDown.value = false
}

// 开始录音
const startRecordingProxy = () => {
  isMouseDown.value = true
  startRecording()
}

// 停止录音
const stopRecordingProxy = () => {
  isMouseDown.value = false
  stopRecording()
}

// 处理录音取消
const handleRecordCancel = () => {
  if (recordingTime > 1) {
    // 如果录音时间超过1秒，显示确认弹窗
    cancelRecordDialogVisible.value = true
  } else {
    // 否则直接取消
    isMouseDown.value = false
    stopRecording()
  }
}

// 继续录音
const continueRecording = () => {
  cancelRecordDialogVisible.value = false
  isMouseDown.value = true
}

// 确认取消录音
const confirmCancelRecording = () => {
  cancelRecordDialogVisible.value = false
  isMouseDown.value = false
  stopRecording()
}

// 确认结束会话
const confirmEndChat = () => {
  endDialogVisible.value = true
}

// 结束会话
const endChat = () => {
  endDialogVisible.value = false
  endConsultation()
  router.push('/')
}

// 格式化时间
const formatTime = (date) => {
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}
</script>

<style scoped>
.consult-chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 60px); /* 减去导航栏高度 */
  padding: 20px;
  box-sizing: border-box;
  position: relative;
}

/* 顶部进度条 */
.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px 15px;
  border-bottom: 1px solid #f0f0f0;
}
.progress-info {
  flex: 1;
  max-width: 500px;
}
.progress-text {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #666;
}
.end-btn {
  color: #f56c6c;
}
.end-btn:hover {
  color: #e4393c;
}

/* 对话内容区 */
.chat-content {
  display: flex;
  flex: 1;
  gap: 20px;
  padding: 20px 10px;
  overflow: hidden;
}

/* 数字人区域 */
.chat-human {
  flex: 0 0 220px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  gap: 15px;
}
.human-status {
  padding: 5px 15px;
  background-color: rgba(59, 130, 246, 0.1);
  color: #3B82F6;
  border-radius: 20px;
  font-size: 14px;
}

/* 对话气泡区 */
.chat-bubbles {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding-right: 10px;
}

/* 输入区 */
.chat-input {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px 10px;
  border-top: 1px solid #f0f0f0;
}
.input-tools {
  display: flex;
  align-items: center;
  gap: 10px;
}
.voice-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  min-width: unset;
  display: flex;
  align-items: center;
  justify-content: center;
}
.recording-time {
  font-size: 14px;
  color: #f56c6c;
  min-width: 30px;
}
.input-box {
  flex: 1;
  border-radius: 20px;
}
.send-btn {
  min-width: 80px;
  border-radius: 20px;
  background-color: #3B82F6;
  border-color: #3B82F6;
}
.send-btn:hover {
  background-color: #2563EB;
  border-color: #2563EB;
}

/* 连接状态提示 */
.connection-status {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

/* 动画定义 */
@keyframes listening {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.03); }
}
@keyframes speaking {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-5px); }
}

/* 响应式适配 */
@media (max-width: 768px) {
  .chat-content {
    gap: 10px;
  }
  .chat-human {
    flex: 0 0 120px;
  }
  .chat-bubbles {
    gap: 10px;
  }
}
</style>